<?php
/**
 * Created by : PhpStorm
 * User: lihb
 * Date: 2023/6/28
 * Time: 11:05
 */
namespace app\api\controller;
use think\App;
use think\Controller;
use think\facade\Request;
use app\api\logic\Tool as ToolLogic;
use app\api\logic\Common as CommonLogic;
use think\facade\Session;
class Tool extends Controller
{
    private $toolLogic;
    public function __construct(App $app = null,ToolLogic $toolLogic)
    {
        parent::__construct($app);
        $this->toolLogic=$toolLogic;
    }

    protected $failException = true;

    public function refresh_token(){
        $token=Request::header('refreshToken');
        if(empty($token)) return json(['msg'=>'token为空','code'=>ERRNO['PARAMERR']]);
        $info=verification($token,2);
        $userInfo=$info['data'];
        if($userInfo->id!=session('userId')) return json(['msg'=>'用户数据错误','code'=>ERRNO['OTHERERR']]);
        $data['id']=$userInfo->id;
//        $data['username']=$userInfo->username;
        $data['type']=$userInfo->type;
        $data['country']=$userInfo->country;
        $access_token=getToken($data);
        Session::set('userId',$userInfo->id);
//        Session::set('userName',$userInfo->username);
        Session::set('userType',$userInfo->type);
        Session::set('country',$userInfo->country);
        return json(['data'=>$access_token,'code'=>ERRNO['OK'],'msg'=>'refresh success']);
    }

    public function modify_phone(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.phone');
        $result=$this->toolLogic->phone($data);
        if($result['req']==0){
            return json(['msg'=>$result['msg'],'code'=>ERRNO['OTHERERR']]);
        }else{
            return json(['data'=>true,'code'=>ERRNO['OK'],'msg'=>'modify success']);
        }

    }

    public function modify_email(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.email');
        $result=$this->toolLogic->email($data);
        if($result['req']==0){
            return json(['msg'=>$result['msg'],'code'=>ERRNO['OTHERERR']]);
        }else{
            return json(['data'=>true,'code'=>ERRNO['OK'],'msg'=>'modify success']);
        }

    }

    public function send_email(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.send');
        if($this->toolLogic->send($data)){
            return json(['data'=>true,'code'=>ERRNO['OK'],'msg'=>'send success']);
        }else{
            return json(['msg'=>'fail in send','code'=>ERRNO['OTHERERR']]);
        }
    }

    public function modify_password(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.password');
        $this->toolLogic->password($data);
        return json(['data'=>true,'code'=>ERRNO['OK'],'msg'=>'modify success']);
    }

    public function countries(){
        $word=$this->request->param('word','');
        $data=$this->toolLogic->countries($word);
        return json(['data'=>$data,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function airports(){
        $data['country_id']=$this->request->param('country_id','');
        $data['word']=$this->request->param('word','');
        $this->validate($data,'app\api\validate\Tool.airports');
        $data=$this->toolLogic->airports($data);
        return json(['data'=>$data,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function categories(){
        $data=$this->toolLogic->categories();
        return json(['data'=>$data,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function materials(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.materials');
        $res=$this->toolLogic->materials($data['type']);
        return json(['data'=>$res,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function phone_code(){
        $res=$this->toolLogic->phoneCode();
        return json(['data'=>$res,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function check_code(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.code');
        $res=CommonLogic::checkCode($data,$data['type'],$data['role']);
        if($res['req']==1){
            return json(['data'=>true,'code'=>ERRNO['OK'],'msg'=>'ok']);
        }else{
            return json(['msg'=>$res['msg'],'code'=>ERRNO['OTHERERR']]);
        }
    }

    public function upload(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.upload');
        if(!isset($_FILES['file']) || $_FILES['file']['size']==0){
            return json(['msg'=>'Please upload a source','code'=>ERRNO['PARAMERR']]);
        }

        $res=$this->toolLogic->upload($data);
        if($res){
            return json(['data'=>$res,'code'=>ERRNO['OK'],'msg'=>'ok']);
        }else{
            return json(['msg'=>'upload error','code'=>ERRNO['OTHERERR']]);
        }
    }

    public function uploads(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.uploads');
        if(!isset($_FILES['file']) || $_FILES['file']['size'][0]==0){
            return json(['msg'=>'file cannot be empty','code'=>ERRNO['OTHERERR']]);
        }

        $res=$this->toolLogic->uploads($data);
        if($res){
            return json(['data'=>$res,'code'=>ERRNO['OK'],'msg'=>'ok']);
        }else{
            return json(['msg'=>'upload error','code'=>ERRNO['OTHERERR']]);
        }

    }

    public function labels(){
        $res=$this->toolLogic->labels();
        return json(['data'=>$res,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function sendSms(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.sendSms');
        $code=mt_rand(1000,9999);
        $code=1234;
        require Env('root_path') . 'vendor/aws/'.'aws-autoloader.php';
//        $credentials = new Credentials('AKIAZCL7BD4M4RNNQVO2', '66HV8YLHk+4sYDP8RbgytnRgLZlPgGFIIuDvXtpU');
        $SnSclient = new SnsClient([
            //'profile' => 'default',
            'region' => 'us-west-1',
            'version' => 'latest',
            //'credentials'=>$credentials
            'credentials'=>[
                'key'=>'AKIAZCL7BD4M4RNNQVO2',
                'secret'=>'66HV8YLHk+4sYDP8RbgytnRgLZlPgGFIIuDvXtpU'
            ]
        ]);
        $message = 'This message is sent from a Amazon SNS code sample.';
        $phone = '+8618884852074';

        try {
//            $result = $SnSclient->publish([
//                'Message' => $message,
//                'PhoneNumber' => $phone,
//            ]);

            $data['code']=$code;
            // 添加记录
            if($this->toolLogic->addCode($data)){
                return json(['data'=>'','code'=>ERRNO['OK'],'msg'=>'ok']);
            }else{
                return json(['msg'=>'send error','code'=>ERRNO['OTHERERR']]);
            }
        } catch (AwsException $e) {
            // output error message if fails
            error_log($e->getMessage());
        }

    }

    /**
     * 获取基础应用信息
     */
    public function system(){
        $data['uri']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/';
        return json(['data'=>$data,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function content(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.content');
        $content=$this->toolLogic->getContent($data['key']);
        return json(['data'=>$content,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    public function qrCode() {
        $uuid=$this->toolLogic->getUuid();
        return json(['data'=>$uuid,'code'=>ERRNO['OK'],'msg'=>'ok']);
    }

    //扫码获取uuid的二维码
    //拿着解析出来的uuid带着user_id请求handleCode生成临时token
    //确认登录后，code表生成登录token，给被扫码设备获取
    public function handleCode() {
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.qrCode');

        $res=$this->toolLogic->handleCode($data);
        if($res==-1){
            return json(['msg'=>'Scan code login expired','code'=>ERRNO['QRCODEERR']]);
        }else{
            return json(['data'=>$res,'code'=>ERRNO['OK']]);
        }
    }

    public function getCode(){
        $data=$this->request->param();
        $this->validate($data,'app\api\validate\Tool.getCode');

        $res=$this->toolLogic->getCode($data);
        if($res){
            return json(['data'=>$res,'code'=>ERRNO['OK']]);
        }else{
            return json(['msg'=>'The result is empty','code'=>ERRNO['RESULTEMPTY']]);
        }
    }
}